//
//  KAFlutterManager.swift
//  kano
//
//  Created by Frank on 2024/10/11.
//

import Foundation
import Flutter

class KAFlutterManager: NSObject {
    
    class func showFlutterVC(route: String, parameter: Dictionary<String, Any>, methodHandler: FlutterMethodCallHandler? = nil) {
        let currentVC = UIViewController.ka_current()
        
        let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
        
        //flutterVC
        let flutterVC = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
        flutterVC.modalPresentationStyle = .fullScreen
        flutterVC.navigationController?.navigationBar.isHidden = true
        
        //methodChannel
        let methodChannel: FlutterMethodChannel = FlutterMethodChannel(name: "swiftkashplay/channel", binaryMessenger: flutterVC.binaryMessenger)
        //methodChannel.setMethodCallHandler(methodHandler)
        methodChannel.setMethodCallHandler({
            (call: FlutterMethodCall, result: FlutterResult) -> Void in
   
            switch call.method {
            case "fromFlutter":

                let params = call.arguments as? [String : Any]
                let action = params!["action"]! as? String
                let param = params!["params"]! as? [String : Any]
                if (action == "toHome") {
                    //to home
                    if currentVC.navigationController?.viewControllers.contains(where: { $0.isKind(of: KAHomeVC.self) }) == false {
                        currentVC.navigationController?.popToRootViewController(animated: true)
                        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                            let var_tabbarVC : UITabBarController = UIViewController.ka_rootViewController()
                            var_tabbarVC.selectedIndex = 0
                        }
                    }
                } else if (action == "toBill") {
                    //to bill
                    guard let isBack = param?["back"] as? Bool else {
                        //currentVC.navigationController?.pushViewController(KABillListVC(), animated: true)
                        return
                    }
                    if isBack {
                        //currentVC.navigationController?.popViewController(animated: true)
                    } else {
                        currentVC.navigationController?.pushViewController(KABillListVC(), animated: true)
                    }
                } else if (action == "toLogin") {
                    KAUserManager.shared.userLogout()
                } else if (action == "toMy") {
                    currentVC.navigationController?.popToRootViewController(animated: true)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                        let var_tabbarVC : UITabBarController = UIViewController.ka_rootViewController()
                        var_tabbarVC.selectedIndex = 1
                    }
                } else if (action == "toLoanContact") {
                    loanAgreement(params: param!, currentVC: currentVC)
                } else if (action == "toBillDetails") {
                    let vc = KABillDetailVC(with: param?["loanGid"] as! String)
                    currentVC.navigationController?.pushViewController(vc, animated: true)
                } else if (action == "analysis") {
                    let event = param?["event"] as! String
                    KAAFTool.logEvent(event: event)
                } else if (action == "outLog") {
                    KAReport.ka_reportWith(type: .log, data: param ?? [:])
                }
            default:
                result(FlutterMethodNotImplemented)
            }
            
//            guard let count = (call.arguments as? NSDictionary)?["count"] as? Int else {
//                result(FlutterError(code: "INVALID_ARGUMENT", message: "Value of count cannot be null", details: nil))
//                return
//            }
            
//            guard let params = (call.arguments as? [String: String]) else {
//                return
//            }
//            guard let count = (call.arguments as? NSDictionary)?["count"] as? Int else {
//                result(FlutterError(code: "INVALID_ARGUMENT", message: "Value of count cannot be null", details: nil))
//                return
//            }
        })
        
        let installDate = UserDefaults.standard.value(forKey: "InstallTime") as? Date
        let installTime = installDate?.ka_timeInterval()
        
        
        
        var urlParam = NetConfig.urlParam()
        urlParam.updateValue(NetConfig.readDomin(), forKey: "domain")
        urlParam.updateValue(KAUserManager.shared.user.userStatus, forKey: "userStatus")
        urlParam.updateValue(installTime ?? 0, forKey: "installTime")
        if let json = KADBDBManager.ka_getObject(by: "homeInfo") as? String {
            let homeInfo = json.kj.model(KAHomeInfo.self)
            urlParam.updateValue(homeInfo?.registerTime ?? 0, forKey: "registerTime")
        }
        urlParam.merge(parameter) { (_, new) in new }
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: urlParam, options: .prettyPrinted)
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                let argument = ["route" : route, "data" : jsonString]
                //Tell Flutter the corresponding page
                methodChannel.invokeMethod("routeTo", arguments: argument)
                
                //UIViewController.ka_current().present(flutterVC, animated: true)
                currentVC.navigationController?.pushViewController(flutterVC, animated: true)
            }
        } catch {
            print("Error converting dictionary to JSON: \(error)")
        }
    }
    
    //跳转借款协议
    class func loanAgreement(params: [String : Any], currentVC: UIViewController) {
        UIViewController.ka_current().view.showLoading()
        let paraDic: [String : Any] = [
            "userGid": KAUserManager.shared.user.userGid,
            "loanGid" : "1234"
        ]
        billProvider.request(.loanAgreement(paraDic)) { result in
            UIViewController.ka_current().view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAAgreemetModel>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
      
                            let model = KABillDetailModel()
//                            let loanDay = "\(String(describing: params["loanDay"]))"
                            model.loanTime = params["loanDate"] as! TimeInterval / 1000
                            model.loanLeftAmount = params["loanMoney"] as! Double
                            model.loanPeriod = params["loanDay"] as! Int
                            model.dueDateArr = params["repaymentDate"] as! [TimeInterval]
                            model.creditAddress = content.creditAddress
                            model.userName = content.userName
                            currentVC.navigationController?.pushViewController(KALoanAgreement(with: model), animated: true)
                        }
                    }
                }else {
                    UIViewController.ka_current().view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}
